package cn.flying.cloud.core.auth.handler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.Rt;
import cn.flying.cloud.core.auth.details.UserDetail;
import cn.flying.cloud.system.common.service.UserService;
import cn.flying.cloud.system.log.entity.SysLoginLog;

/**
 * @description: 登出成功处理类
 * @author: admin
 * @date: 2023年05月27日 10:47
 * @version: 1.0
 */
@Component
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取当登录用户信息
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        logger.info("租户【{}】的用户【{}-{}】退出系统登录成功！", userDetail.getTenantId(), userDetail.getUserId(), userDetail.getUsername());

        try {
            //保存登录日志
            SysLoginLog log = new SysLoginLog();
            log.setUserId(userDetail.getUserId());
            log.setUserName(userDetail.getUsername());
            log.setName(userDetail.getName());
            log.setHappenType("用户注销");
            log.setHappenTime(LocalDateTime.now());
            log.setHappenIp(Ft.Network.getIpAddress(request));
            log.setRemark("用户成功退出系统");
            log.setTenantId(userDetail.getTenantId());
            log.setCreatedBy(userDetail.getUsername());
            log.setCreatedTime(LocalDateTime.now());
            log.setUpdatedBy(userDetail.getUsername());
            log.setUpdatedTime(LocalDateTime.now());
            log.setRevision(0L);
            userService.insertLoginLog(log);
        } catch (Exception e) {
            logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
        }

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(Rt.success(RtCodeEnum.R10006.getDesc())));
        out.flush();
        out.close();
    }
}
